import os
from docx import Document
import re
from docx.shared import Pt
from docx.oxml.ns import qn

def is_standalone_picture(paragraph):
    """检测段落是否只包含图片（独立成行）"""
    if paragraph.text.strip() != "":
        return False
    
    for run in paragraph.runs:
        if '<pic:pic' in run._element.xml:
            return True
    return False

def create_caption(text, number):
    """创建图注文本"""
    return f'图{number} {text}' if text else f'图{number}'

def process_docx_file(input_path, output_path):
    print(f"📄 正在处理：{os.path.basename(input_path)}")
    try:
        doc = Document(input_path)
    except Exception as e:
        print(f"❌ 读取失败：{e}")
        return

    # 收集所有独立图片段落的位置
    picture_paragraphs = []
    for i, para in enumerate(doc.paragraphs):
        if is_standalone_picture(para):
            picture_paragraphs.append(i)
    
    if len(picture_paragraphs) <= 3:
        print("⚠️ 文档中只有3张或更少的图片，跳过处理")
        try:
            doc.save(output_path)
            print(f"✅ 保存成功：{os.path.basename(output_path)}")
        except Exception as e:
            print(f"❌ 保存失败：{e}")
        return
    
    picture_paragraphs = picture_paragraphs[:-3]
    
    image_number = 1
    offset = 0
    
    for i, pos in enumerate(picture_paragraphs):
        actual_pos = pos + offset
        
        # 查找所有相关的描述段落
        caption_text = ""
        caption_para = None
        desc_paras = []  # 存储所有描述段落
        
        # 检查后续段落，直到遇到图片或文档结束
        current_index = actual_pos + 1
        while current_index < len(doc.paragraphs):
            current_para = doc.paragraphs[current_index]
            
            # 如果遇到图片，停止收集
            if is_standalone_picture(current_para):
                break
                
            # 检查是否是图注编号段落
            if re.match(r'^图\s*\d+\s*$', current_para.text.strip()):
                caption_para = current_para
                current_index += 1
                continue
            
            # 收集描述段落
            if current_para.text.strip() != "":
                desc_paras.append(current_para)
                caption_text += current_para.text.strip() + " "
            
            current_index += 1
        
        # 清理多余空格
        caption_text = caption_text.strip()
        
        # 处理图注
        if caption_para or desc_paras:
            # 如果存在图注编号段落，使用它作为基础
            if caption_para:
                target_para = caption_para
            else:
                # 否则使用第一个描述段落
                target_para = desc_paras[0]
                desc_paras = desc_paras[1:]  # 移除已使用的段落
            
            # 更新图注内容
            target_para.clear()
            run = target_para.add_run(create_caption(caption_text, image_number))
            
            # 设置字体为仿宋四号
            run.font.size = Pt(14)
            run.font.name = "仿宋"
            r = run._element
            r.rPr.rFonts.set(qn('w:eastAsia'), '仿宋')
            
            target_para.alignment = 1  # 居中
            
            # 删除多余的描述段落
            for para in desc_paras:
                if para in doc.paragraphs:  # 确保段落仍然存在
                    para._p.getparent().remove(para._p)
                    offset -= 1  # 更新偏移量
        else:
            # 没有找到图注或描述，添加新图注
            new_para = doc.add_paragraph()
            run = new_para.add_run(create_caption("", image_number))
            run.font.size = Pt(14)
            run.font.name = "仿宋"
            r = run._element
            r.rPr.rFonts.set(qn('w:eastAsia'), '仿宋')
            new_para.alignment = 1
            
            # 应用原始段落样式
            orig_para = doc.paragraphs[actual_pos]
            if orig_para.style:
                new_para.style = orig_para.style
            
            # 移动到正确位置
            new_p = new_para._p
            orig_p = orig_para._p
            orig_p.addnext(new_p)
            offset += 1
        
        image_number += 1

    try:
        doc.save(output_path)
        print(f"✅ 保存成功：{os.path.basename(output_path)}")
    except Exception as e:
        print(f"❌ 保存失败：{e}")

def batch_process_folder(folder_path):
    output_dir = os.path.join(folder_path, "output")
    os.makedirs(output_dir, exist_ok=True)

    files = [f for f in os.listdir(folder_path) if f.endswith(".docx") and not f.startswith("~$")]
    if not files:
        print("⚠️ 没有找到 .docx 文件")
        return

    for filename in files:
        input_path = os.path.join(folder_path, filename)
        output_path = os.path.join(output_dir, f"{os.path.splitext(filename)[0]}_编号.docx")
        process_docx_file(input_path, output_path)

    print("\n📁 所有文件处理完成！输出保存在：", output_dir)

# # === 修改这里为你的目标文件夹路径 ===
# target_folder = r"G:\剑河县鉴定报告\Test"
# batch_process_folder(target_folder)
# === 修改这里为你的目标文件夹路径 ===
target_folder = r"G:\剑河县鉴定报告\PythonTest"
batch_process_folder(target_folder)